package com.mooc.ppjoke.ui.sofa;

import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.mooc.libnavannoation.FragmentDestination;
import com.mooc.ppjoke.data.SofaTab;
import com.mooc.ppjoke.databinding.FragmentSofaBinding;
import com.mooc.ppjoke.ui.home.HomeFragment;
import com.mooc.ppjoke.utils.AppConfig;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: SofaFragment$
 * @Description: java类作用描述
 * @Author: 魏靳元
 * @CreateDate: 2022/8/14 20:01
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
@FragmentDestination(pageUrl = "main/tabs/sofa")
public class SofaFragment extends  Fragment{
    private FragmentSofaBinding binding;
    protected TabLayout tabLayout;
    protected ViewPager2 viewPage;
    private List<SofaTab.TabsBean> tabs;
    private SofaTab sofaTab;
    private Map<Integer,Fragment> map=new HashMap<>();
    private TabLayoutMediator mediator;

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        binding = FragmentSofaBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    public SofaTab getTabConfig() {
        return AppConfig.getSofaTab();
    }
    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        viewPage = binding.viewPage;
        tabLayout = binding.tabLayout;
        sofaTab = AppConfig.getSofaTab();
        tabs = new ArrayList<>();
        for (SofaTab.TabsBean tab :sofaTab.getTabs()) {
            if (tab.getEnable()) {
                tabs.add(tab);
            }
        }
        
        viewPage.setOffscreenPageLimit(ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT);
        viewPage.setAdapter(new FragmentStateAdapter(getChildFragmentManager(),this.getLifecycle()) {
            @Override
            public int getItemCount() {
                return tabs.size();
            }

            @NonNull
            @NotNull
            @Override
            public Fragment createFragment(int position) {
//                Fragment fragment = map.get(position);
//                if(fragment==null){
//                    fragment=getTabFragment(position);
//                    map.put(position, fragment);
//                }
                return getTabFragment(position);
            }
        });
        tabLayout.setTabGravity(sofaTab.getTabGravity());
        mediator = new TabLayoutMediator(tabLayout, viewPage, false, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull @NotNull TabLayout.Tab tab, int position) {
                tab.setCustomView(createTabView(position));
            }
        });
        mediator.attach();//保持tab和viewpager联动
        viewPage.registerOnPageChangeCallback(changeCallback);
        viewPage.post(new Runnable() {
            @Override
            public void run() {
                viewPage.setCurrentItem(sofaTab.getSelect());
            }
        });

    }
    ViewPager2.OnPageChangeCallback changeCallback=new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            int tabCount=tabLayout.getTabCount();
            for (int i = 0; i < tabCount; i++) {
                TabLayout.Tab tabAt = tabLayout.getTabAt(i);
                assert tabAt != null;
                TextView textView = (TextView) tabAt.getCustomView();
                if(tabAt.getPosition() == position){
                    assert textView != null;
                    textView.setTextSize(sofaTab.getActiveSize());
                    textView.setTypeface(Typeface.DEFAULT_BOLD);
                }else {
                    assert textView != null;
                    textView.setTextSize(sofaTab.getNormalSize());
                    textView.setTypeface(Typeface.DEFAULT);
                }

            }
        }
    };

    private View createTabView(int position) {
        TextView textView = new TextView(getContext());
        int[][] states=new int[2][];
        states[0]=new int[]{android.R.attr.state_selected};
        states[1]=new int[]{};
        int[] colors = new int[]{Color.parseColor(sofaTab.getActiveColor()), Color.parseColor(sofaTab.getNormalColor())};
        ColorStateList stateList = new ColorStateList(states, colors);
        textView.setTextColor(stateList);
        textView.setText(tabs.get(position).getTitle());
        textView.setTextSize(sofaTab.getNormalSize());
        return textView;
    }

    public Fragment getTabFragment(int position) {

        return HomeFragment.newInstance(tabs.get(position).getTag());
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        List<Fragment> fragments = getChildFragmentManager().getFragments();
        for (Fragment fragment : fragments) {
            if (fragment.isAdded() && fragment.isVisible()) {
                fragment.onHiddenChanged(hidden);
                break;
            }
        }
    }

    @Override
    public void onDestroy() {
        mediator.detach();
        viewPage.unregisterOnPageChangeCallback(changeCallback);
        super.onDestroy();

    }
}